<?php
namespace App\Services;

use App\Models\Coupon;
use App\Models\CouponSn;
use App\Models\SystemControl;
use App\Models\User;
use Illuminate\Support\Facades\DB;

/**
 *
 * 优惠券服务层
 *
 * @author maqu
 *
 */
class CouponService extends BaseService {

    /**
     * 获取优惠券列表
     *
     * @param $user_id  用户ID
     * @param $listtype 列表 0-all 1-可用 2-已用 3-过期
     * @param $firstrow
     * @param $pagesize
     *
     * @return mixed
     */
    public function getMyCouponList($user_id,$listtype,$firstrow,$pagesize){

        $now = gmtime();

        $temp_arr=[];

        $user = User::find($user_id);
        if(!$user){
            return $this->failure('用户不存在');
        }

        switch($listtype){
            case COUPON_USEFUL;//1-可用
                $coupon_sns =$user->couponSns()
                    ->where('coupon_sn.remain_times','>',0)
                    ->where('coupon_sn.start_time','<=',$now)
                    ->where('coupon_sn.end_time','>=',$now)
                    ->with(['coupon' => function ($query) use($now) {
                        $query->where('coupon.if_issue',1)
                        ->select("coupon_id","coupon_name","coupon_value","min_amount","if_issue");
                    }])->skip($firstrow)->take($pagesize)
                    ->get();

                break;
            case COUPON_USED;//2-已用
                $coupon_sns =$user->couponSns()
                    ->where('coupon_sn.remain_times',0)
                    ->where('coupon_sn.start_time','<=',$now)
                    ->with(['coupon' => function ($query) use($now) {
                        $query->where('coupon.if_issue',1)
                            ->select("coupon_id","coupon_name","coupon_value","min_amount","if_issure");
                    }])->skip($firstrow)->take($pagesize)
                    ->get();

                break;
            case COUPON_OVERDUE;//3-过期
                $coupon_sns =$user->couponSns()
                    ->where('coupon_sn.remain_times','>',0)
                    ->join('coupon','coupon.coupon_id','=','coupon_sn.coupon_id')
                    ->where('coupon_sn.end_time','<',$now)
                    ->where('coupon.if_issue',1)
                    ->skip($firstrow)->take($pagesize)
                    ->with(['coupon' => function ($query) use($now) {
                        $query->where('coupon.if_issue',1)
                            ->select("coupon_id","coupon_name","coupon_value","min_amount","if_issue");
                    }])
                    ->get();

                break;
            default;
                $coupon_sns =$user->couponSns()
                    ->with(['coupon' => function ($query) use($now) {
                        $query->where('coupon.if_issue',1)
                            ->select("coupon_id","coupon_name","coupon_value","min_amount","if_issue");
                    }])->skip($firstrow)->take($pagesize)
                    ->get();

                break;
        }

        $temp_arr =$coupon_sns->toArray();
        $time = gmtime();
        foreach($temp_arr as $k=>$v){

            $temp_arr[$k]['coupon_status']=1;

            if($v['remain_times']<=0){
                $temp_arr[$k]['coupon_status']=3;
            }

            if($v['end_time']<$time){
                $temp_arr[$k]['coupon_status']=2;
            }

            $temp_arr[$k]['end_time'] = local_date('Y-m-d',$v['end_time']);
            unset($temp_arr[$k]['coupon_id']);
            unset($temp_arr[$k]['pivot']);
        }

        return $temp_arr;
    }

    /**
     * 获取优惠券列表
     *
     * @param $user_id  用户ID
     * @param $listtype 列表 0-all 1-可用 2-已用 3-过期
     *
     * @return mixed
     */
    public function getMyCouponCount($user_id,$listtype = 0){

        $now = gmtime();

        $count=0;

        switch($listtype){
            case COUPON_USEFUL;//1-可用
                $count =User::find($user_id)->couponSns()
                    ->where('coupon_sn.remain_times','>',0)
                    ->with(['coupon' => function ($query) use($now) {
                        $query->where('coupon.start_time','<=',$now)
                            ->where('coupon.end_time','>=',$now)
                            ->where('coupon.if_issue',1);
                    }])
                    ->count();

                break;
            case COUPON_USED;//2-已用
                $count =User::find($user_id)->couponSns()
                    ->where('coupon_sn.remain_times',0)
                    ->with(['coupon' => function ($query) use($now) {
                        $query->where('coupon.if_issue',1)
                            ->where('coupon.start_time','<=',$now);
                    }])
                    ->count();

                break;
            case COUPON_OVERDUE;//3-过期

                $count =User::find($user_id)->couponSns()
                    ->where('coupon_sn.remain_times','>',0)
                    ->join('coupon','coupon.coupon_id','=','coupon_sn.coupon_id')
                    ->where('coupon.end_time','<',$now)
                    ->where('coupon.if_issue',1)
                    ->with(['coupon' => function ($query) use($now) {
                        $query->where('coupon.end_time','<',$now)
                            ->where('coupon.if_issue',1);
                    }])
                    ->count();

                break;
            default;
                $count =User::find($user_id)->couponSns()
                    ->with(['coupon' => function ($query) use($now) {
                        $query->where('coupon.if_issue',1);
                    }])
                    ->count();

                break;
        }

        return $count;
    }

    public function getReceiveableCouponList($store_id,$user_id,$firstrow,$pagesize){

        $now = gmtime();

        $data =Coupon::where('coupon.if_issue',1)
            ->where('coupon.store_id',$store_id)
            ->where('coupon.coupon_type',COUPON_TYPE_RECEIVEABLE)
            ->skip($firstrow)->take($pagesize)
            ->orderBy('end_time','asc')
            ->get();

        $coupon_ids=[];

        if($user_id){
            $coupon_ids = User::find($user_id)->couponSns()->get()->pluck('coupon_id')->toArray();
        }

        foreach ($data as $item){
            //todo 移除已经超过使用期限的优惠券

            if(!empty($item->coupon_logo)){
                $item->coupon_logo = complete_url($item->coupon_logo);
            }
            if($user_id){
                $item->received = in_array($item->coupon_id, $coupon_ids)?1:0;
            } else {
                $item->received = 0;
            }

        }

        return $data->toArray();

    }

    public function getRandomCoupon($store_id,$user_id,$firstrow,$pagesize){

        $now = gmtime();

        $data =Coupon::where('coupon.start_time','<=',$now)
            ->where('coupon.end_time','>=',$now)
            ->where('coupon.if_issue',1)
            ->where('coupon.store_id',$store_id)
            ->where('coupon.coupon_type',COUPON_TYPE_RECEIVEABLE)
            ->get();

        $coupon_ids=[];

        if($user_id){
            $coupon_ids = User::find($user_id)->couponSns()->get()->pluck('coupon_id')->toArray();
        }

        foreach ($data as $item){
            if(!empty($item->coupon_logo)){
                $item->coupon_logo = complete_url($item->coupon_logo);
            }
            if($user_id){
                $item->received = in_array($item->coupon_id, $coupon_ids)?1:0;
            } else {
                $item->received = 0;
            }

        }

        return $data->toArray();

    }

    public function isReceived($user_id,$coupon_id){
        return User::find($user_id)->couponSns()->where('coupon_id',$coupon_id)->count()>0?true:false;
    }

    public function generate($coupon,$prefix,$pid_length=8)
    {
        $control = SystemControl::findOrNew(1);

        $cpm = sprintf('%0'.$pid_length.'d', $control->coupon_create_pid?$control->coupon_create_pid:1);
        $tmp = mt_rand(1000, 9999);
        $couponsn = $prefix . $cpm . $tmp;

        $add_data = array(
            'coupon_sn' => $couponsn,
            'coupon_id' => $coupon->coupon_id,
            'remain_times' => $coupon->use_times,
            'start_time' => 0,
            'end_time' => 0
        );

        if($coupon->valid_type == COUPON_VALID_TYPE_FROM_TO){//如果有效时间为自定义日期
            $add_data['start_time'] = $coupon->start_time;
            $add_data['end_time'] = $coupon->end_time;
        }elseif($coupon->valid_type == COUPON_VALID_TYPE_DATE){//如果有效时间为自定义天数
            $start_time = gmtime();
            $end_time = $start_time + 86400 * $coupon->valid_date;
            $add_data['start_time'] = $start_time;
            $add_data['end_time'] = $end_time;
        }else{
            $add_data['start_time'] = $coupon->start_time;
            $add_data['end_time'] = $coupon->end_time;
        }

        $control->coupon_create_pid++;

        $control->save();

        DB::table('coupon_sn')->insert(
            $add_data);

        return $add_data;
    }

    /**
     * 获取购物结算时可使用优惠券列表
     *
     * @param $user_id  用户ID
     * @param $amount 结算金额
     * @param $firstrow
     * @param $pagesize
     *
     * @return mixed
     */
    public function getCashierCouponList($user_id,$amount,$firstrow,$pagesize){

        $now = gmtime();

        $temp_arr=[];

        $coupon_sns =User::find($user_id)->couponSns()
            ->join('coupon', 'coupon.coupon_id', '=', 'coupon_sn.coupon_id')
            ->where('coupon_sn.remain_times','>',0)
            ->where('coupon.start_time','<=',$now)
            ->where('coupon.end_time','>=',$now)
            ->where('coupon.min_amount','<=',$amount)
            ->where('coupon.if_issue',1)
            ->orderBy('coupon.end_time','asc')
            ->skip($firstrow)->take($pagesize)
            ->select('coupon_sn.coupon_sn','coupon_sn.remain_times','coupon.coupon_name','coupon.end_time','coupon.coupon_value')
            ->get();
        $temp_arr = $coupon_sns->toArray();

        foreach($temp_arr as $k=>$v){
            unset($temp_arr[$k]['coupon_id']);
            unset($temp_arr[$k]['pivot']);
        }

        return $temp_arr;
    }

    /**
     * 获取购物结算时默认使用优惠券
     *
     * @param $user_id  用户ID
     * @param $amount 结算金额
     * @return mixed
     */
    public function getCashierCouponMethods($user_id,$amount){

        $now = gmtime();

        $temp_arr=[];

        $coupon_sns =User::find($user_id)->couponSns()
            ->join('coupon', 'coupon.coupon_id', '=', 'coupon_sn.coupon_id')
            ->where('coupon_sn.remain_times','>',0)
            ->where('coupon.start_time','<=',$now)
            ->where('coupon.end_time','>=',$now)
            ->where('coupon.min_amount','<=',$amount)
            ->where('coupon.if_issue',1)
            ->orderBy('coupon.end_time','asc')
            ->select('coupon_sn.coupon_sn','coupon_sn.remain_times','coupon.coupon_name','coupon.end_time','coupon.coupon_value')
            ->first();
        if($coupon_sns){
            $temp_arr = $coupon_sns->toArray();
            unset($temp_arr['coupon_id']);
            unset($temp_arr['pivot']);
        }

        return $temp_arr;
    }

    /**
     * 获取优惠券信息
     *
     * @param $coupon_sn 优惠券编号
     * @return $coupon_info 优惠券信息
     */
    public function getCouponInfo($coupon_sn){

        $coupon_info = CouponSn::with('coupon')
            ->where('coupon_sn',$coupon_sn)
            ->first();
//        $coupon_info = DB::table('coupon_sn')->join('coupon','coupon_sn.coupon_id','=','coupon.coupon_id')
////                        ->where('coupon.store_id',$store_id)
//            ->where('coupon_sn.coupon_sn',$coupon_sn)
//            ->select('coupon.*','coupon_sn.remain_times')->first();
//        dd($coupon_info);
        return $coupon_info;
    }

    public function send($coupon_id,$user_ids){

        if(!$coupon_id || !$user_ids){
            $this->failure('参数不对');
        }

        $coupon = Coupon::find($coupon_id);
        if(!$coupon){
            $this->failure('优惠券不存在');
        }

        foreach ($user_ids as $user_id)
        {
            $arr = $this->generate($coupon,'SN');

            DB::table('user_coupon')->insert([
                'user_id'=>$user_id,
                'coupon_sn'=>$arr['coupon_sn']
            ]);
        }
        $this->success(null);

    }

}